<script setup lang="ts">
import img from '../assets/微信图片_20230708224126.jpg'
import {TeamType} from "../models/Team";
import {teamStatusEnum} from "../constants/team.ts";
import { showToast} from "vant";
import {onMounted, ref} from "vue";
import {useRouter} from "vue-router";
import {showConfirmDialog} from "vant/es";
import {deleteTeam, joinTeam, quitTeam} from "@/api/team.ts";
import {getCurrentUser} from "@/api/user.ts";

interface TeamCartListProps {
  teamList: TeamType[];
}
const props = withDefaults(defineProps<TeamCartListProps>(),{
  teamList: [] as TeamType[],
})

// 加入队伍
const teamId = ref<number>()
const password = ref('')
const show = ref(false)
const prePassword = (status:number,id:number) => {
  teamId.value = id
  if(status !== 0){
    show.value = true
  }else {
    doJoinTeam()
  }
}
const doJoinTeam = async () => {
  const res = await joinTeam(password.value, teamId.value)
  if(res.data.code === 0 && res.data.data){
    showToast('加入成功！')
    password.value = ''
    emit('changeData')
  }else {
    showToast('加入失败！'+'\n'+ res.data.description)
  }
}
const cancelJoinTeam = () => {
  password.value = ''
  // show.value = false
}

const currentUser = ref()
// 获取用户数据
const getUserInfo = async () => {
  const res = await getCurrentUser()
  currentUser.value = res.data
}
onMounted(() => getUserInfo() )
const router = useRouter()

// 传给父组件
const emit = defineEmits(['changeData'])

// 更新按钮
const doUpdateTeam = (id:number) => {
  router.push({
    path: '/team/update/',
    query: {
      id: id
    }
  })
}
// 解散队伍
const doDelTeam = (id:number) => {
  showConfirmDialog({
    title: '标题',
    message:
        '确定要解散队伍吗',
    closeOnPopstate: false,
  })
      .then(async () => {
        const res = deleteTeam(id)
        if ((await res).data.code === 0 && (await res).data.data) {
          showToast('已解散队伍')
          emit('changeData')
        }
      })
}
// 退出队伍
const doQuitTeam = (id:number) => {
  showConfirmDialog({
    title: '标题',
    message:
        '确定要退出队伍吗',
  })
      .then(async () => {
        const res = await quitTeam(id)
        if (res.data.code === 0 && res.data.data) {
          showToast('已退出队伍')
          emit('changeData')
        }
      })
      .catch(() => {
        // on cancel
      });
}

// 队伍详情
const detail = (id:number) => {
  router.push({
    path: '/team/detail',
    query: {
      id
    }
  })
}

// 下拉刷新
const loading = ref(false);
const onRefresh = () => {
  setTimeout(() => {
    loading.value = false;
  }, 1000);
};
</script>

<template>
  <van-pull-refresh
    v-model="loading"
    success-text="刷新成功"
    @refresh="onRefresh"
  >
    <div class="teamCartList">
      <van-card
          v-for="team in props.teamList"
          :desc="team.description"
          :title="team.name"
      >
        <template #thumb>
          <van-image
            width="88"
            height="88"
            fit="cover"
            :src="team.coverImage ?? img"
            @click=detail(team.id)
          />
        </template>
        <template #tags>
          <van-tag @click=detail(team.id) plain type="danger">
            {{ teamStatusEnum[team.status] }}
          </van-tag>
        </template>
        <template #bottom>
          <div @click=detail(team.id)>
            {{ '队伍人数：'+ team.hasJoinNum + '/' + team.maxNum}}
          </div>
          <div @click=detail(team.id)>
            {{ '过期时间：' + (team.expireTime??'永不过期')}}
          </div>
        </template>
        <template #footer>
          <van-button v-if="team.userId !== currentUser.data?.id && !team.hasJoin" size="small" type="primary" plain @click="prePassword(team.status,team.id)">
            加入
          </van-button>
          <van-button v-if="team.userId === currentUser.data?.id" @click="doUpdateTeam(team.id)" size="small" type="success" plain>更新队伍</van-button>
          <van-button v-if="team.userId === currentUser.data?.id" @click="doDelTeam(team.id)" size="small" type="danger" plain>解散队伍</van-button>
          <van-button v-if="team.userId !== currentUser.data?.id && team.hasJoin" @click="doQuitTeam(team.id)" size="small" type="danger" plain>退出队伍</van-button>
          <div>
            <van-dialog v-model:show="show" title="请输入密码" @confirm="doJoinTeam" @cancel="cancelJoinTeam" show-cancel-button>
              <van-field v-model="password" placeholder="请输入密码"/>
            </van-dialog>
          </div>
        </template>
      </van-card>
    </div>
  </van-pull-refresh>
</template>

<style scoped>

</style>